const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
  showMsg
} from '../../../../utils/config.js'
import {
  validateEmoji,
  validateSpecial
} from '../../../../utils/validate.js'
import {
  reqSpaceEdit,
  reqSpaceImage,
  reqDeviceBySpaceId,
  reqDeviceByImei,
  reqDeviceAdd,
  reqDeviceUnBind,
  reqAlarmReceiverList,
  reqReceiverSpaceAdd,
  reqAlarmReceiverBySpaceId
} from '../../../../request/api'
Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    parkId: '', //园区id
    form: {
      id: '',
      name: '',
      address: '',
      isDefence: false,
      buildingType: 3, //空间类型 
      orgId: ""
    },
    imageList: [],
    imageCount: 6, //照片数量限制6张
    disabledBtn: false,
    // 接警人开始
    showPeopleCall: false,
    alarmReceiverList: [],
    alarmPage: 1,
    alarmIsNextPage: true,
    alarmReceiverArr: [], //最终提交值id集合
    selAlarmReceiverArr: [], //展示渲染页面
    alarmReceiverIdList1: [],
    alarmReceiverIdList2: [],
    alarmReceiverIdList3: [],
    alarmReceiverIdList4: [],

    expanded: true,
    level: 1,
    levelList: [{
        value: 1,
        name: "一级",
      },
      {
        value: 2,
        name: "二级",
      },
      {
        value: 3,
        name: "三级",
      },
      {
        value: 4,
        name: "四级",
      },
    ],
    // 接警人结束
  },
  onLoad(e) {
    // console.log(JSON.parse(e.item));
    this.getItemInfo(e)
  },
  onShow() {
    this.getSpaceImage() //获取照片信息
    this.getAlarmReceiverBySpaceId() //空间id获取安装设备
    this.AlarmReceiverBySpaceId() //空间id获取接警人列表
    this.getAlarmReceiverList() //获取接警人列表
  },
  // 获取信息
  getItemInfo(e) {
    let item = JSON.parse(e.item)
    this.setData({
      parkId: item.parkId,
      'form.id': item.id,
      'form.name': item.name,
      'form.address': item.address,
      'form.isDefence': item.isDefence === 1 ? true : false,
      'form.orgId': item.orgId,
    })
  },

  /* --------------------------------设备开始-------------------------- */
  // 空间id获取安装设备
  async getAlarmReceiverBySpaceId() {
    const res = await reqDeviceBySpaceId(this.data.form.id)
    let {
      rows
    } = res.data
    let arr = []
    rows.forEach((item, index) => {
      arr.push({
        id: index,
        devicePrimaryId: item.id,
        imei: item.imei,
        type: item.productName,
      })
    })
    this.setData({
      imeiList: arr
    })
  },
  // 点击新增一条设备输入框
  clickAddDevice() {
    let {
      imeiList
    } = this.data
    let count = 0
    let length = imeiList.length
    imeiList.forEach(item => {
      if (item.devicePrimaryId) {
        count++
      }
    })
    if (length - count >= 5) return showMsg("一次最多新增5台设备")
    // let id = imeiList[imeiList.length - 1].id + 1
    let id = imeiList.length === 0 ? 0 : imeiList[imeiList.length - 1].id + 1
    imeiList.push({
      id,
      imei: '',
      type: ''
    })
    this.setData({
      imeiList
    })
  },
  // 判断imei是否已存在
  async getDeviceByImei(id, imei) {
    let {
      imeiList
    } = this.data
    const res = await reqDeviceByImei(imei)
    if (res.code === 12020 || res.code === 12021) {
      // 清空操作
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = ''
          item.type = ''
        }
      })
      // imeiList.forEach(item => {
      //     if (item.id === id) {
      //         item.imei = imei
      //         // item.type = res.data.row.productName
      //     }
      // })
      this.setData({
        imeiList
      })
      showMsg(res.message)
      return
    }
    if (res.code !== 20000) return showMsg(res.message)
    imeiList.forEach(item => {
      if (item.id === id) {
        item.imei = imei
        item.type = res.data.row.productName
      }
    })
    this.setData({
      imeiList
    })
    this.reqReceiverSpace() // 安装点设备修改
  },
  // 获取设备imei
  imeiChange(e) {
    let {
      id
    } = e.target.dataset
    let {
      value
    } = e.detail
    if (value.length >= 15) {
      this.getDeviceByImei(id, value)
    }
    if (value.length <= 0) {
      // 删除到没有时，清除imei和类型
      let {
        imeiList
      } = this.data
      imeiList.forEach(item => {
        if (item.id === id) {
          item.imei = ''
          item.type = ''
        }
      })
      this.setData({
        imeiList
      })
    }
  },
  // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    console.log('It is not a string!')
  },
  /**
   * @name:  扫码imei
   * @msg: 掉接口时记得询问清楚截取方法
   * @return {*}
   */
  imeiScan(e) {
    let that = this
    let {
      id
    } = e.target.dataset
    let qrcode = ''
    wx.scanCode({
      success(res) {
        qrcode = res.result;
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 3) {
          if (that.isjson(qrcode)) {
            const result = JSON.parse(qrcode);
            // JSON字符格式
            that.setData({
              searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
            })
            that.getDeviceByImei(id, result.ID)
          } else {
            // 非JSON格式
            that.setData({
              searchValue: qrcode,
            })
            that.getDeviceByImei(id, qrcode)
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
  // 扫码后赋值imei
  imeiScanChange(id, code) {
    let {
      imeiList
    } = this.data
    imeiList.forEach(item => {
      if (item.id === id) {
        item.imei = code
      }
    })
    this.setData({
      imeiList
    })
  },
  // 清除imei
  imeiClear(e) {
    let {
      info
    } = e.target.dataset
    let {
      imeiList
    } = this.data
    imeiList.forEach((item, index) => {
      if (item.id === info.id) {
        if (info.devicePrimaryId) {
          this.getDeviceUnBind(info.devicePrimaryId, index)
        } else {
          item.imei = ''
          item.type = ''
        }
      }
    })
    this.setData({
      imeiList
    })
  },

  getDeviceUnBind(id, index) {
    let {
      imeiList
    } = this.data
    Dialog.confirm({
        title: '温馨提示',
        message: '此操作将解绑该设备，是否继续？',
      })
      .then(async () => {
        const res = await reqDeviceUnBind({
          userId: app.globalData.userId,
          id
        })
        if (res.code != 20000) return showMsg(res.message);

        imeiList.splice(index, 1)
        imeiList.forEach((item, index) => {
          item.id = index
        })
        this.setData({
          imeiList
        })
        showMsg("解绑成功")
      })
      .catch(() => {});
  },

  // 确定修改设备
  async reqReceiverSpace() {
    let {
      imeiList,
      form
    } = this.data
    let arr = imeiList.map(item => {
      return item.imei
    })
    let list = arr.filter(Boolean)
    if (list.length <= 0) return showMsg("请输入设备编码")
    let params = {
      spaceId: this.data.form.id,
      userId: app.globalData.userId,
      imeiList: list
    }
    const res = await reqDeviceAdd(params)
    if (res.code != 20000) return showMsg(res.message);
    // showMsg("编辑成功", "success")
    // this.setData({
    //     disabledBtn: true
    // })
    // setTimeout(() => {
    //     wx.navigateBack({
    //         delta: 1,
    //     })
    // }, 2000)
  },


  /* --------------------------------设备结束-------------------------- */


  // 获取照片信息
  async getSpaceImage() {
    let list = this.data.imageList
    if (list.length > 0) return
    const res = await reqSpaceImage(this.data.form.id)
    if (res.code != 20000) return showMsg(res.message);
    let {
      rows
    } = res.data
    if (rows && rows.length <= 0) return
    let imageList = []
    rows.forEach((item, index) => {
      imageList.push({
        id: index,
        src: item
      })
    })
    this.setData({
      imageList,
      imageCount: 6 - imageList.length
    })
  },
  // 点击布撤防
  changeDefence(e) {
    let tip = e.detail ? '此操作将开启该安装点所有设备布防设置，是否继续？' : '此操作将关闭该安装点所有设备布防设置，是否继续？'
    Dialog.confirm({
        title: '温馨提示',
        message: tip,
      })
      .then(async () => {
        this.setData({
          "form.isDefence": e.detail
        })
      })
      .catch(() => {});
  },
  // 单个添加获取名称
  nameChange(e) {
    // 正则表达式
    //  let value = e.detail.value.replace(/[^\-\d]/g, ""); // 只能输入-和数字
    //  value = value.replace(/\-{2,}/g, "-"); // -只能保留一个
    //  value = value.replace(/(\d)\-/g, "$1"); // 数字后面不能接-，不能出现类似-11-2,12-，11-23
    //  value = value.replace(/-(0+)/g, "0"); // 不能出现-0,-001,-0001类似
    //  value = value.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
    //  if(value>50){
    //     value=50
    //  }
    //  if(value<-3){
    //     value=-3
    //  }
    //  if(value=='0'){
    //     value=1
    //  }
    this.data.form.name = validateEmoji(e.detail.value.replace(/\s+/g, ''))
    this.setData({
      "form.name": this.data.form.name
    })
  },
  // 单个添加清除
  clearname() {
    this.setData({
      'form.name': ''
    })
  },

  // ------------照片开始
  addImage() {
    let {
      imageList
    } = this.data
    if (imageList.length >= 6) return showMsg("安装照片最多添加6张")
    this.uploadFileFun()
  },
  uploadFileFun(updateItem) {
    let that = this
    wx.chooseImage({
      count: this.data.imageCount,
      success(res) {
        // console.log(res);

        var PicNums = res.tempFiles.length;
        for (var inta = 0; inta < PicNums; inta++) {
          var path = res.tempFiles[inta].path;
          var formatImage = path.split(".")[(path.split(".")).length - 1];
          console.log("图片格式" + formatImage)
          // 判断格式
          if (formatImage != "png" && formatImage != "jpg") {
            showMsg("只能上传.png、.jpg格式")
          }
          // 判断大小
          let size = res.tempFiles.every(item => { //限制上传图片大小为2M,所有图片少于2M才能上传  
            return item.size <= 20000000 //return item.size <= 2000000  500000
          })
          console.log(size);
          if (!size) {
            showMsg("图片大小不能超过20MB!")
            return;
          }
        }


        const tempFilePaths = res.tempFilePaths
        if (tempFilePaths.length > 6) return showMsg("安装照片最多添加6张")

        tempFilePaths.forEach(item => {
          wx.uploadFile({
            url: app.globalData.reqUrl + 'file/upload',
            filePath: item,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            formData: {
              "token": app.globalData.token,
              "file": item,
            },
            success: function (res) {
              let data = JSON.parse(res.data)
              // console.log(data);
              if (data.code == 20000) {
                that.updateImageList(data.data.url, updateItem)
                return showMsg("上传成功")
              } else {
                return showMsg("上传失败")
              }
            },
            fail: function (e) {
              return showMsg("上传失败")
            }
          })
        })

      }
    })
  },
  // 上传成功后更新照片列表
  updateImageList(url, updateItem) {
    let {
      imageList
    } = this.data
    if (updateItem && updateItem.src) {
      // 更新图片
      imageList.forEach(citem => {
        if (citem.id === updateItem.id) {
          citem.src = url
        }
      })
      imageList.forEach((citem, index) => {
        citem.id = index
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })

    } else {
      // 添加图片 
      // console.log(imageList.length);
      let id = 0
      if (imageList.length > 0) {
        id = imageList.length
      }
      imageList.push({
        id,
        src: url
      })
      this.setData({
        imageList,
        imageCount: 6 - imageList.length
      })
    }

    // console.log(this.data.imageList);
  },

  // 点击照片  发生的操作：预览、编辑、删除
  iamgeClick(e) {
    let {
      item
    } = e.currentTarget.dataset
    let that = this
    wx.showActionSheet({
      itemList: ['预览图片', '更新图片'],
      success(res) {
        let {
          tapIndex
        } = res
        if (tapIndex === 0) {
          that.previewImageFun(item)
        } else if (tapIndex === 1) {
          that.updateImageFun(item)
        } else {
          that.delImageFUn(item)
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  // 1、预览图片
  previewImageFun(item) {
    let {
      imageList
    } = this.data
    let urls = imageList.map(item => {
      return item.src
    })
    wx.previewImage({
      current: item.src, // 当前显示图片的http链接
      urls, // 需要预览的图片http链接列表
    })
  },
  // 2、更新图片
  updateImageFun(item) {
    this.uploadFileFun(item)
  },
  // 3、删除图片
  delImageFUn(e) {
    let {
      item
    } = e.currentTarget.dataset
    let {
      imageList
    } = this.data
    imageList.forEach(citem => {
      if (citem.id === item.id) {
        imageList.splice(item.id, 1)
      }
    })
    imageList.forEach((citem, index) => {
      citem.id = index
    })
    this.setData({
      imageList,
      imageCount: 6 - imageList.length
    })
  },
  // ------------照片结束

  // 确认编辑楼层
  async confirm() {
    if (this.data.disabledBtn) return
    let {
      form,
      imageList
    } = this.data
    if (imageList.length > 6) return showMsg("安装照片最多添加6张")
    let picList = imageList.map(item => {
      return item.src
    })
    if (!(form.name)) return showMsg("请输入名称")
    if (!validateSpecial(form.name)) return
    let params = {
      parkId: this.data.parkId,
      id: form.id,
      name: form.name,
      lng: '',
      lat: '',
      province: '',
      provinceCode: '',
      city: '',
      cityCode: '',
      area: '',
      areaCode: '',
      street: '',
      streetCode: '',
      address: '',
      isDefence: form.isDefence ? 1 : 0,
      buildingType: form.buildingType,
      picList,
      village: ''
    }
    // await this.reqReceiverSpace() // 安装点设备修改
    // await this.receiverSpaceAddFun() //接警人新增
    await this.reqSpaceAddFun(params)
  },
  // 单个添加
  async reqSpaceAddFun(params) {
    const res = await reqSpaceEdit(params)
    if (res.code != 20000) return showMsg(res.message);
    showMsg("编辑成功", "success")
    this.setData({
      disabledBtn: true
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 1,
      })
    }, 2000)
  },


  // -----------------接警人开始----------------
  // 空间id获取接警人列表
  async AlarmReceiverBySpaceId() {
    const res = await reqAlarmReceiverBySpaceId(this.data.form.id)
    let {
      rows
    } = res.data
    if (rows && rows.length) {
      rows.sort((a, b) => a.level - b.level)
      this.setData({
        selAlarmReceiverArr: rows
      })
    } else {
      this.setData({
        selAlarmReceiverArr: []
      })
    }
  },

  //展开/收缩接警人
  togglePanel() {
    this.setData({
      expanded: !this.data.expanded
    });
  },

  // 点击展示接警人弹窗
  async clickShowPeopleCall(e) {
    // console.log(e.currentTarget.dataset.value);
    const res = await reqAlarmReceiverBySpaceId(this.data.form.id)
    // 复选框渲染已有的接警人
    let {
      rows
    } = res.data;
    // console.log(rows);
    // console.log(this.data.alarmReceiverArr.length);
    // 只有第一次进来才选中状态
    // if (rows.length != this.data.alarmReceiverArr.length) {
    rows.forEach((result, index) => {
      console.log(result.level == e.currentTarget.dataset.value);
      // 勾选对应级别的接警人
      if (result.level == e.currentTarget.dataset.value) {
        const checkbox = this.selectComponent(`.checkboxes-${result.id}`);
        checkbox.toggle();
      }
    })
    // }
    // 级别禁用
    let arr = []
    if (e.currentTarget.dataset.value == 1) {
      arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList4]
    } else if (e.currentTarget.dataset.value == 2) {
      arr = [...this.data.alarmReceiverIdList1, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList4]
    } else if (e.currentTarget.dataset.value == 3) {
      arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList1, ...this.data.alarmReceiverIdList4]
    } else if (e.currentTarget.dataset.value == 4) {
      arr = [...this.data.alarmReceiverIdList2, ...this.data.alarmReceiverIdList3, ...this.data.alarmReceiverIdList1]
    }
    // console.log(arr);
    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      arr.forEach(item2 => {
        if (item.id == item2.id) {
          item.disabled = true;
        }
      })
      return item
    })
    // console.log(list);
    this.setData({
      showPeopleCall: true,
      valueInfo: e.currentTarget.dataset.value,
      alarmReceiverList: list, //级别禁用
    })
  },
  // 点击关闭接警人弹窗
  async closePeopleCall() {
    //   清空选中的状态
    this.data.alarmReceiverArr.forEach((result, index) => {
      console.log(result);
      const checkbox = this.selectComponent(`.checkboxes-${result}`);
      checkbox.toggle();
    })

    let list = this.data.alarmReceiverList.map(item => {
      item.disabled = false;
      return item
    })
    this.setData({
      showPeopleCall: false,
      alarmReceiverList: list, //取消禁用
    })
  },
  //接警人新增
  async receiverSpaceAddFun() {
    let {
      selAlarmReceiverArr,
    } = this.data

    let alarmReceiverIdList1 = []
    let alarmReceiverIdList2 = []
    let alarmReceiverIdList3 = []
    let alarmReceiverIdList4 = []
    selAlarmReceiverArr.forEach((item) => {
      switch (item.level) {
        case 1:
          alarmReceiverIdList1.push(item.id)
          break
        case 2:
          alarmReceiverIdList2.push(item.id)
          break
        case 3:
          alarmReceiverIdList3.push(item.id)
          break
        case 4:
          alarmReceiverIdList4.push(item.id)
          break
        default:
          return
      }
    })
    if (alarmReceiverIdList1.length > 6) return showMsg("一级接警人最多设置6个")
    if (alarmReceiverIdList2.length > 6) return showMsg("二级接警人最多设置6个")
    if (alarmReceiverIdList3.length > 6) return showMsg("三级接警人最多设置6个")
    if (alarmReceiverIdList4.length > 6) return showMsg("四级接警人最多设置6个")
    const res = await reqReceiverSpaceAdd({
      spaceId: this.data.form.id,
      alarmReceiverIdList1,
      alarmReceiverIdList2,
      alarmReceiverIdList3,
      alarmReceiverIdList4,
    })
    if (res.code != 20000) return showMsg(res.message);
  },

  /**
   * @name: 获取接警人列表
   * @return {*}
   */
  async getAlarmReceiverList() {
    let params = {
      orgId: this.data.form.orgId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
    }
    const res = await reqAlarmReceiverList(this.data.alarmPage, 99, params)
    if (res.code !== 20000) return showMsg(res.message, "error")
    let {
      rows
    } = res.data
    console.log(rows);
    if (this.data.alarmPage === 1) {
      this.setData({
        alarmReceiverList: rows,
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && rows.length) {
      this.setData({
        alarmReceiverList: this.data.alarmReceiverList.concat(rows),
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && !rows.length) {
      showMsg('已经到底啦~')
      this.setData({
        alarmIsNextPage: false
      })
    }
    if (this.data.showPeopleCall) {
      this.clickShowPeopleCall()
    }
  },

  // 滚动到底部触发
  alarmReceiverLower() {
    if (!this.data.alarmIsNextPage) return
    this.setData({
      alarmPage: this.data.alarmPage + 1,
    })
    this.getAlarmReceiverList()
  },

  levelChange(event) {
    this.setData({
      level: event.detail,
    });
  },
  // 获取alarmReceiverArr的值
  deviceChange(event) {
    this.setData({
      alarmReceiverArr: event.detail
    })
    // console.log(this.data.alarmReceiverArr,"alarmReceiverArr")
  },
  // 点击获取alarmReceiverArr的值
  deviceToggle(event) {
    const {
      id
    } = event.currentTarget.dataset;
    this.checkboxChange(id)
  },
  // 复选框变化渲染
  checkboxChange(id) {
    console.log(id);
    const checkbox = this.selectComponent(`.checkboxes-${id}`);
    checkbox.toggle();
  },

  // 删除某个接警人
  deleteAlarmReceiver(e) {
    const {
      id,
      value
    } = e.currentTarget.dataset;

    let {
      alarmReceiverArr,
      selAlarmReceiverArr
    } = this.data
    alarmReceiverArr.forEach((item, index) => {
      if (item.id === id) {
        alarmReceiverArr.splice(index, 1)
      }
    })
    selAlarmReceiverArr.forEach((item, index) => {
      if (item.id === id) {
        selAlarmReceiverArr.splice(index, 1)
      }
    })
    this.setData({
      alarmReceiverArr,
      selAlarmReceiverArr
    })
    this.checkboxChange(id)
    this.receiverSpaceAddFun() //接警人新增
  },
  // 确定选择接警人
  async confirmPeopleCall() {
    let {
      alarmReceiverArr,
    } = this.data
    // if (alarmReceiverArr.length > 6) return showMsg("接警人最多设置6个")
    const res = await reqReceiverSpaceAdd({
      spaceId: this.data.form.id,
      alarmReceiverIdList1: this.data.valueInfo == 1 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList1.map(item => item.id),
      alarmReceiverIdList2: this.data.valueInfo == 2 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList2.map(item => item.id),
      alarmReceiverIdList3: this.data.valueInfo == 3 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList3.map(item => item.id),
      alarmReceiverIdList4: this.data.valueInfo == 4 ? this.data.alarmReceiverArr : this.data.alarmReceiverIdList4.map(item => item.id),
    })
    if (res.code != 20000) return showMsg(res.message);
    // await this.receiverSpaceAddFun()
    await this.closePeopleCall() //关闭弹窗
    this.AlarmReceiverBySpaceId() // 空间id获取接警人列表
  },

  // 去新增接警人
  // goAddAlarmReceiver() {
  //     let {
  //         spaceId,
  //         spaceName
  //     } = this.data
  //     let info = {
  //         spaceId,
  //         spaceName
  //     }
  //     let params = JSON.stringify(info)
  //     wx.navigateTo({
  //         url: `/packageA/pages/index-inside-page/alarm-receiver-add/alarm-receiver-add?params=${params}`,
  //     })
  // },

})